<template>
	<agent-shop-select-table
		ref="agentShopSelectTableRef"
		v-model="value"
		:title="t('选择代理商店铺')"
		:service="service.order.shop"
		:columns="columns"
		:multiple="true"
		:dict="{ text: 'name', value: 'id' }"
		:shopNameList="shopNameList"
		pickerType="text"
	/>
</template>

<script setup lang="ts">
defineOptions({
	name: 'agent-shop-select'
});

import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { CrudProps } from '/#/crud';
import { reactive, ref, useModel, watch } from 'vue';
import AgentShopSelectTable from './agent-shop-select-table.vue';

const props = defineProps({
	...CrudProps,
	modelValue: null,
	multiple: Boolean,
	agentObj: {
		type: Object,
		default: () => ({})
	}
});

const { service } = useCool();
const { t } = useI18n();

const value = useModel(props, 'modelValue');

const shopNameList = ref([]);

// 监听agentObj变化，更新modelValue
watch(
	() => props.agentObj,
	newAgentObj => {
		console.log('Agent shop select - agentObj changed:', newAgentObj);
		if (newAgentObj && newAgentObj.agentShopIds) {
			// 当agentObj变化时，将agentShopIds设置为modelValue
			value.value = newAgentObj.agentShopIds;
			shopNameList.value = newAgentObj.agentShopName.split(',') || [];
		}
	},
	{ immediate: true, deep: true }
);

// 店铺选择表格组件引用
const agentShopSelectTableRef = ref();

// 清空表格数据
const clearTableData = () => {
	if (agentShopSelectTableRef.value && agentShopSelectTableRef.value.clearData) {
		agentShopSelectTableRef.value.clearData();
	}
};

defineExpose({
	clearTableData
});

const columns = ref([
	{ label: t('ID'), prop: 'id', minWidth: 140 },
	{ label: t('店铺名称'), prop: 'name', minWidth: 140 },
	{ label: t('地址'), prop: 'address', minWidth: 140 }
]);
</script>
